
package com.alibaba.luohua.common.core.web.controller;


import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * web层通用数据处理
 *
 * @author luohua
 * @date 2022年3月14日21:11:50
 */
@Slf4j
public class BaseController {


    /**
     * 下载Zip文件
     *
     * @param files
     * @param zipFileName
     * @param response
     */
    public static void downloadZipFile(List<File> files, String zipFileName, HttpServletResponse response) {
        byte[] buf = new byte[1024];
        BufferedOutputStream bos = null;
        ZipOutputStream out = null;
        try {

//			response.reset(); // 重点突出

            bos = new BufferedOutputStream(response.getOutputStream());
            out = new ZipOutputStream(bos);

            // 不同类型的文件对应不同的MIME类型
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));

            for (File file : files) {
                FileInputStream in = new FileInputStream(file);
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(file.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }

            log.info("压缩完成...");

        } catch (Exception e) {
            log.error("下载文件异常，原因：", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("关闭文件异常，原因：", e);
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    log.error("关闭文件异常，原因：", e);
                }
            }
        }
    }

}
